﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Nox.Amuse.Helpers;

namespace Nox.Amuse.Model
{
    [XmlRoot("Index")]
    public class DataIndex
    {
        /// <summary>
        /// The file name template for this class to be saved under when serialized
        /// </summary>
        const string FileName = "Index.xml";

        [XmlArray("Worlds"), XmlArrayItem("WorldName")]
        public List<string> WorldNames = new List<string>();

        /// <summary>
        /// Private Constructor
        /// </summary>
        private DataIndex()
        { }

        /// <summary>
        /// Attempts to Load settings from the disk and push them in to a new instance. If file is not found, loads defaults.
        /// </summary>
        /// <returns>A new settings model</returns>
        public static DataIndex Load()
        {
            var serializer = new XmlSerializer(typeof(DataIndex));
            var textReader = FileHelper.StartReadingTextFile(FileName);
            if (textReader != null)
            {
                try
                {
                    return (DataIndex)serializer.Deserialize(textReader);
                }
                catch
                {
                    return new DataIndex();
                }
                finally
                {
                    textReader.Close();
                }
            }
            else
                return new DataIndex();
        }

        /// <summary>
        /// Saves the data
        /// </summary>
        public void Save()
        {
            var serializer = new XmlSerializer(typeof(DataIndex));
            var writer = FileHelper.StartWritingTextFile(FileName);
            serializer.Serialize(writer, this);
            writer.Close();
        }
    }
}
